<template>
  <div class="home">
    <div class="operationBar">

      <span class="login" @click="goToPage('/login')" v-if="isLocalDb !== 'false'">登录</span>

      <span class="role" v-else>
        <img :src="selector" alt="">
        角色信息
      </span>

      <div style="color:#646cff" @click="downloadApp"> 下载手机版app </div>

      <div class="deepBtn">
        开启深度模式
        <img :src="eye" alt="">
      </div>
    </div>

    <div class="thingsList" @click="goToThingsList">
      <ul>
        <li v-for="(item,index) in paperTags" :key="index">
            <img :src="item" alt="">
        </li>
      </ul>
      <div>
        事项清单
      </div>
    </div>

    <div class="recentPlan">
      <ul class="box">
        <li style="marginBottom:10px">
          <span style="fontSize:20px">近期计划</span>
          <span style="fontSize:16px" @click="goToPage('/to-do-tasks')">更多>></span>
        </li>
        <li>
          <span>计划1</span>
          <span>
            截止时间 
            <span class="endTime">2025.5.1</span>
          </span>
          <span>
            剩余
            <span class="remainTime">1 周</span>
          </span>
        </li>
        <li>
          <span>计划1</span>
          <span>
            截止时间
            <span class="endTime">2025.5.1</span>
          </span>
          <span>
            剩余
            <span class="remainTime">1 周</span>
          </span>
        </li>

        <li>
          <span>计划1</span>
          <span>
            截止时间
            <span class="endTime">2025.5.1</span>
          </span>
          <span>
            剩余
            <span class="remainTime">1 周</span>
          </span>
        </li>
        
      </ul>
    </div>

    <div>
      <ul class="navList">
        <li @click="goToMine"><span>我的</span></li>
        <li @click="goToPage('/to-do-tasks')"> <span>待办</span></li>
        <li  @click="goToPage('/settings')"><span>设置</span></li>
      </ul>
    </div>

    <div class="currentStatus">
      <div class="status">
        <span class="title"> 学习中 </span>
        <br>
        <span class="tips"> 预计2小时后结束 </span>
        <br>
        <span class="immersion">沉浸模式</span>
      </div>
      <div class="operation">提前终止</div>
    </div>

    <div class="speakBox" v-if="AIStatus == 'stand'">
      <div class="speak" v-if="!isChatting">
        <span>Hello，我是AI小熊，今天你有什么计划吗？</span><br>
        <span style="float:right;color:#e39b80" @click="startSpeak">开始对话</span>
      </div>

      <div class="isChatingBox" v-if="isChatting">
        <div class="header">
          <span @click="collapseSession">收起</span>
          <span @click="deleteHistoryConversition">清空历史会话</span>
        </div>
        <div class="content">
          <div v-if="isLocalDb !== 'false'">你还没有登录哦！点击<span style="color:red" @click="goToPage('/login')">登录</span>后查看更多吧!</div>
          <ul v-else class="sessionList">

            <li v-for="item in sessionList"  :key="item.id" :class="item.type === 'AI' ? 'AIAgent' : 'user' ">
               <span>{{item.type === 'AI' ? 'AI小熊' : '我' }}</span>  
              <span>{{item.content}}</span>
            </li>

        
            <li class="AIAgent" v-if="currentAnswer">
              <span>AI小熊</span>  
              <span>{{currentAnswer}}</span>
            </li> 
            
          </ul>
        </div>

        <div class="inputBox">
          <div contenteditable="true" ref="inputMessage" class="input"></div>
          <span v-if="!isLoading" class="send" @click="sendMessage" >发送</span>
          <span v-else class="send" >会话处理中</span>

        </div>
      </div>
    </div>


    <div class="AIBear">
      <img v-show="AIStatus == 'slope'" class="slope" :src="bear3" alt="" @click="changeAIStatus('stand')">
      <img  v-show="AIStatus == 'stand'" class="stand" :src="bear1" alt="" @click="changeAIStatus('slope')">
    </div>
    
  </div>

  <div class="downloadingLine" v-if="isDownLoading">
    下载中......
    <a-progress strokeColor="#5fb3b3" trailColor="rgba(255,255,255,0.68)" :percent="downloadPercent" :width="100" :strokeWidth="15" />
  </div> 

</template>

<script setup lang="ts">
import {useRouter,useRoute} from "vue-router";
import {  LeftOutlined} from '@ant-design/icons-vue';
import {ref,onMounted, reactive} from 'vue'

import bear3 from '@/assets/imgs/bear3.png'
import bear1 from '@/assets/imgs/bear1.png'
import eye from '@/assets/imgs/eye.png'
import selector from '@/assets/imgs/selector.png'

import bluePaper from '@/assets/imgs/paperTags/bluePaper.png'
import greenPaper from '@/assets/imgs/paperTags/greenPaper.png'
import orangePaper from '@/assets/imgs/paperTags/orangePaper.png'
import pinkPaper from '@/assets/imgs/paperTags/pinkPaper.png'

import {startChat} from '@/api/handleAiChat.js'

import {sendMessageApi,
        saveMessageApi,
        searchConversitionListApi,
        deleteHistoryConversitionApi
} from "@/api/handleAiChat.js"

import {  
  searchUserInfoApi
} from '@/api/handleUserAccount.js'

import {
  getLatestAppInfoApi,
  downloadAppApi
} from '@/api/handleAppVersion.js'

import {useUserStore} from '@/store/user.js'


const store = useUserStore()

const paperTags = [bluePaper,greenPaper,orangePaper,pinkPaper]

const router = useRouter()

const AIStatus = ref('slope')
const isChatting = ref(false)

const inputMessage = ref('')

const isLocalDb = ref('true')

const isLoading = ref(false)

const currentAnswer = ref('')

const isDownLoading = ref(false)
const downloadPercent = ref(0)

// 当下临时存储的对话数据---
const sessionList = ref([
  // {
  //   id:1,
  //   content:'请说一下具体的计划目标',
  //   type:'AI',

  // },
  // {
  //   id:2,
  //   content:'我今天的计划是xxx',
  //   type:'user',
  // }
])


const currentSession = reactive({
  sessionId:'',
  question:'',
  answer:'',
  roleCode:''
})

const changeAIStatus=(param)=>{
  AIStatus.value = param
}
const goToMine=()=>{
  if(isLocalDb.value !== 'false'){
    router.push('/login')
  }else{
    router.push('/mine')

  }
}

const goToPage = (path)=>{
    router.push(path)
}


const goToThingsList=()=>{
  if(isLocalDb.value !== 'false'){
    router.push('/login')
  }else{
    router.push('/things-list')
  }
}


const searchConversition = async ()=> {
    sessionList.value = []
    // 在这里调用查询接口
    let roleCode = JSON.parse(sessionStorage.getItem('userInfo')).currentRoleCode
    let res = await searchConversitionListApi({roleCode:roleCode})
    console.log('查询内容',res)

     if(res?.length>0){
      sessionStorage.setItem('sessionId',res[0].sessionId)

      // 解析查询内容，变成对话形式
      res.map((item,index)=>{
        let answer =  item.sessionContent.answer
        let question =  item.sessionContent.question

        let list = [
          {
            id:(res.length - index) * 2 - 1,
            content:question,
            type:'user'
          },
          {
              id:(res.length - index) * 2,
              content:answer,
              type:'AI'
          }
        ]
        sessionList.value.unshift(...list)
      })
    }


}

const startSpeak =async()=>{
  console.log('开始对话')
  isChatting.value = true
  if( sessionList.value.length === 0 && isLocalDb.value === 'false' ){
    await searchConversition()
  }
}


const deleteHistoryConversition = async ()=>{
  sessionStorage.setItem('sessionId','')
  console.log('点击了')
  // deleteHistoryConversitionApi --
   // 在这里调用查询接口
    let roleCode = JSON.parse(sessionStorage.getItem('userInfo')).currentRoleCode
    let res = await deleteHistoryConversitionApi({roleCode:roleCode})
    console.log('删除结果',res)
    if(res){
      // 重新查询会话
      await searchConversition()
    }
}




const collapseSession = ()=>{
  isChatting.value = false
}


const sendMessage = async ()=>{
  currentAnswer.value = '' // 清空当前回答


  if(inputMessage.value.textContent){
    isLoading.value = true
    console.log('发送消息', inputMessage.value.textContent)

    //添加到临时存储中
    currentSession.question = inputMessage.value.textContent

    sessionList.value.push({
      id: sessionList.value.length+1,
      type:'user',
      content:inputMessage.value.textContent,
    })


    let params = {
      content: inputMessage.value.textContent,
      sessionId: sessionStorage.getItem('sessionId') || ''
    }


    inputMessage.value.textContent = ''

    let responseStream = await sendMessageApi(params)


    console.log('获取到的响应内容',responseStream)
  


    if(responseStream){
        
      //ai分析内容，目前没有用到
      let analysis = ''
      let conversation_id = sessionStorage.getItem('sessionId') || ''

      const reader = responseStream?.getReader()
      const decoder = new TextDecoder()
      let done = false
      let thinkStart = false

      while (!done) {
          const { value, done: streamDone } = await reader.read()
          if (streamDone) break
          const chunk = decoder.decode(value, { stream: true })
          // 处理每一行 data: ...\n
          const lines = chunk.split('\n')
          for (let line of lines) {
              line = line.trim()
              if (!line.startsWith('data:')) continue
              let dataStr = line.replace(/^data:\s*/, '')

              if (!dataStr) continue
              let result
              try {
                  result = JSON.parse(dataStr)
              } catch (e) {
                  continue
              }
              if (!conversation_id && result.conversation_id) {
                  sessionStorage.setItem('sessionId',result.conversation_id)
                  conversation_id = result.conversation_id
              }
              if (result.event === 'message') {
                  let ans = result.answer?.replace(/\n/g,'') || ''
                  switch(ans) {
                      case '<think>':
                          thinkStart = true
                          break
                      case '</think>':
                          thinkStart = false
                          ans = ''
                          break
                  }
                  if (thinkStart) {
                      analysis += ans
                  } else {
                      currentAnswer.value += ans
                  }
              }
          }
      }


      sessionList.value.push({
        id: sessionList.value.length+1,
        type:'AI',
        content:currentAnswer.value
      })


     // 数据全部接收完后，将当前内容保存到数据库中
      currentSession.answer = currentAnswer.value
      currentSession.sessionId = sessionStorage.getItem('sessionId')
      currentSession.roleCode = JSON.parse(sessionStorage.getItem('userInfo')).currentRoleCode
      let saveRes = await saveMessageApi(currentSession)
      console.log('保存数据成功内容=====',saveRes)


      currentAnswer.value = ''
    }
    isLoading.value = false

  }else{
    alert('请输入信息')
  }
}

const downloadApp = async ()=>{
   let resInfo = await getLatestAppInfoApi('yrzj')
   const {filePath,version} = resInfo
    if(filePath){
      isDownLoading.value = true
      downloadPercent.value = 0

      let res = await downloadAppApi({remotePath:filePath})

      if(res){
        const totalSize = Number(res.headers.get('Content-Length'));
        let loadedSize = 0;
        let fileName = `一日之计_${version}.apk`;

        const reader = res.body.getReader();

        let chunks:any = []; // 存储下载的块 //返回Unit8Array 二进制数据
        // 读取数据并存储
        async function  read() {
          while(true){
            const { done, value } = await reader.read();
            if (done) {
              break;
            }
            loadedSize += value.length;
            chunks.push(value);
            // 更新进度条
            downloadPercent.value = Math.floor(loadedSize / totalSize * 100)
          }
        }

        await read()


        // 生成blob链接并下载
        const fullArray = new Uint8Array(loadedSize);
        let position = 0;
        for (const chunk of chunks) {
          fullArray.set(chunk, position);
          position += chunk.length;
        }
        const blob = new Blob([fullArray], { type: 'application/octet-stream' });
        const downloadUrl = window.URL.createObjectURL(blob);
        let elink = document.createElement('a');
        elink.href = downloadUrl
        elink.download = fileName;
        document.body.appendChild(elink);
        elink.click();
        document.body.removeChild(elink);
        window.URL.revokeObjectURL(downloadUrl);
      }

      isDownLoading.value = false
      downloadPercent.value = 0
    }
 }

onMounted( async ()=>{
  isLocalDb.value =  sessionStorage.getItem('localDb')
  if(isLocalDb.value === 'false'){
    // 重新更新一下最新的本地用户信息
    let userResult = await searchUserInfoApi()
    store.updateUserInfo(userResult)
  }
})
</script>

<style lang="less" scoped>

.home {
  padding: 15px;
  overflow-x: hidden;
  box-sizing: border-box; 
  min-height: calc(100vh - 30px);
  .operationBar{
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;

    .login{
      border:solid #f1ca67 3px;
      width: 40px;
      height: 40px;
      display: flex;
      justify-content: center;
      align-items: center;
      border-radius: 30px;
      background-color: rgba(255, 255,255, 0.5);
    }

    .role{
      display: flex;
      align-items: center;
      img{
        width: 30px;
        margin-right: 5px;
      }
    }
      
    .deepBtn{
      display: flex;
      align-items: center;
      img{
        width: 25px;
        margin-left: 5px;
      }
    }



  }


  .thingsList{
    width: 65%;
    margin: 30px 0;
    padding: 30px 15px;
    border:solid #ce9f69 20px;
    border-radius: 5px;
    background-color: #334c2c;
    color: white;
    font-weight: bolder;
    font-size:40px;
    letter-spacing: 20px;

    ul{
      display: flex;
      flex-direction: row;
      justify-content: center;
      align-items: center;
      gap: 20px;
      margin:0;

      li{
        img{
          width: 100%;
          height: 45px;
        }
      }
    }
    
  }


  .recentPlan{
    font-size: 17px;
    width: 100%;

    .box{
      display: flex;
      flex-direction: column;
      li{
        display: flex;
        flex-direction: row;
        justify-content: space-between;
        align-items: center;
        
        .endTime,
        .remainTime{
          background:#fff8de;
          padding: 2px 8px;
        }
      }
    }
  }

  .navList{
    position:absolute;
    right: 0;
    top: 120px;
    display: flex;
    flex-direction: column;
    gap: 30px;

    li{
      background-color:#f7ed8e ;
      padding: 0px 30px;

      span{
        border:solid  black 1px;
        padding: 5px;
        background-color: #ecf092;
      }

    }
  }

  

  @media (max-width:575px) {

    .thingsList{
      width: 50%;
      font-size:20px;
      border:solid #ce9f69 12px;
      ul > li{
        img{
          width: 100%;
          height: 30px;
        }
      }
    }

    .navList{
      top: 80px;
      gap: 20px;
      li{
        padding: 0px 20px;
      }
    }
  }


  .currentStatus{
    display: flex;
    flex-direction: column;
    justify-content: space-around;
    
    border: solid 2px;
    width:40vw;
    height:40vw;
    border-radius: 20vw;
    margin: 40px auto 10px;

    .status{
      .title{
        font-size: 24px;
        font-weight: bold;
      }
      .tips{
        font-size: 12px;
      }
      .immersion{
        background: #e0f1f7;
        padding: 2px 5px;
      }
    }
    .operation{
      font-size: 18px;
    }

  }

  .speakBox{
    position: relative;
    display: flex;
    flex-direction: row;
    justify-content: flex-end;

    .speak{
      width:150px;
      background-image:url('@/assets/imgs/bg_speakBox.png');
      background-size:contain ;
      background-repeat: no-repeat;
      background-position: right;
      padding: 20px 55px;
      font-size: 14px;
    }

      
    .isChatingBox{
      box-sizing: border-box;;
      display: flex;
      flex-direction: column;
      position:absolute;
      width:70vw;
      height: 60vh;
      min-height: 250px;
      border-radius: 10px;
      z-index: 999;
      bottom:0;
      right:0;
      font-size: 14px;
      background: rgba(216, 236, 224, 0.95); 

      .header{
        padding: 10px;
        display: flex;
        flex-direction: row;
        justify-content: space-between;
        border-radius: 10px 10px 0 0;;
        background-color: rgba(150,201,219, 0.4);
        font-size:12px;
      }
      
      .content{
        padding:10px;
        text-align: left;
        flex:1 1;
        overflow: auto;;

        .sessionList{
          display: flex;
          flex-direction: column;
          gap:10px;

          > li{
            width:80%;
            display: flex;
            gap:10px;
            :nth-child(1){
              padding: 5px 0;

            }
            :nth-child(2){
              flex:1 1;
              padding: 5px;
              border-radius: 8px;;
            }
          }
          
          .AIAgent{
            flex-direction: row;
            :nth-child(2){
              color:white;
              background: rgba(160,176,213);
            }

          }
          .user{
            align-self: flex-end;
            flex-direction: row-reverse;
            :nth-child(2){
              background: white;
            }
          }

        }
      }


      .inputBox{
        padding:10px;
        display: flex;
        flex-direction: row;
        justify-content: space-between;
        background-color: #f4f4f5;
        border-radius: 0 0 10px 10px;
        gap:10px;
        padding:10px 5px;
        .input{
          outline:none;
          flex:1 1;
          background: white;;
          text-align: left;
          padding:5px 10px;
          max-height:80px;
          overflow-y: auto;
        }
        .send{
          padding:5px 0;
        }
      }
    }
  }


  .AIBear{
    display: flow-root;
    position: relative;
    height: auto;
    border-right: solid 3px #30250a;
    overflow: hidden;

    .slope,
    .stand{
      position: relative;
      float:right;
    }
    .slope{
      width: 150px;
      right: -80px;
    }
    .stand{
      width: 100px;
    }
  }
}

.downloadingLine{
  box-sizing: border-box;
  position: fixed;
  width: 100%;
  height: 100%;
  bottom: 0px;
  left: 50%;
  transform: translateX(-50%);
  background: rgba(0,0,0,0.5);
  padding: 10px 20px;

  color: white;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;

  :deep(.ant-progress){
    .ant-progress-text{
      color:white ;
    }
  }
}


</style>
